home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlsec.z / perlsec
Encoding:
Text File  |  2002-10-03  |  22.1 KB  |  529 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlsec - Perl security
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      Perl is designed to make it easy to program securely even when running
  13.      with extra privileges, like setuid or setgid programs.  Unlike most
  14.      command line shells, which are based on multiple substitution passes on
  15.      each line of the script, Perl uses a more conventional evaluation scheme
  16.      with fewer hidden snags.  Additionally, because the language has more
  17.      builtin functionality, it can rely less upon external (and possibly
  18.      untrustworthy) programs to accomplish its purposes.
  19.  
  20.      Perl automatically enables a set of special security checks, called _t_a_i_n_t
  21.      _m_o_d_e, when it detects its program running with differing real and
  22.      effective user or group IDs.  The setuid bit in Unix permissions is mode
  23.      04000, the setgid bit mode 02000; either or both may be set.  You can
  24.      also enable taint mode explicitly by using the ----TTTT command line flag. This
  25.      flag is _s_t_r_o_n_g_l_y suggested for server programs and any program run on
  26.      behalf of someone else, such as a CGI script. Once taint mode is on, it's
  27.      on for the remainder of your script.
  28.  
  29.      While in this mode, Perl takes special precautions called _t_a_i_n_t _c_h_e_c_k_s to
  30.      prevent both obvious and subtle traps.  Some of these checks are
  31.      reasonably simple, such as verifying that path directories aren't
  32.      writable by others; careful programmers have always used checks like
  33.      these.  Other checks, however, are best supported by the language itself,
  34.      and it is these checks especially that contribute to making a set-id Perl
  35.      program more secure than the corresponding C program.
  36.  
  37.      You may not use data derived from outside your program to affect
  38.      something else outside your program--at least, not by accident.  All
  39.      command line arguments, environment variables, locale information (see
  40.      the _p_e_r_l_l_o_c_a_l_e manpage), results of certain system calls (readdir,
  41.      readlink, the gecos field of getpw* calls), and all file input are marked
  42.      as "tainted".  Tainted data may not be used directly or indirectly in any
  43.      command that invokes a sub-shell, nor in any command that modifies files,
  44.      directories, or processes. (IIIImmmmppppoooorrrrttttaaaannnntttt eeeexxxxcccceeeeppppttttiiiioooonnnn: If you pass a list of
  45.      arguments to either system or exec, the elements of that list are NNNNOOOOTTTT
  46.      checked for taintedness.) Any variable set to a value derived from
  47.      tainted data will itself be tainted, even if it is logically impossible
  48.      for the tainted data to alter the variable.  Because taintedness is
  49.      associated with each scalar value, some elements of an array can be
  50.      tainted and others not.
  51.  
  52.      For example:
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  71.  
  72.  
  73.  
  74.          $arg = shift;               # $arg is tainted
  75.          $hid = $arg, 'bar';         # $hid is also tainted
  76.          $line = <>;                 # Tainted
  77.          $line = <STDIN>;            # Also tainted
  78.          open FOO, "/home/me/bar" or die $!;
  79.          $line = <FOO>;              # Still tainted
  80.          $path = $ENV{'PATH'};       # Tainted, but see below
  81.          $data = 'abc';              # Not tainted
  82.  
  83.          system "echo $arg";         # Insecure
  84.          system "/bin/echo", $arg;   # Secure (doesn't use sh)
  85.          system "echo $hid";         # Insecure
  86.          system "echo $data";        # Insecure until PATH set
  87.  
  88.          $path = $ENV{'PATH'};       # $path now tainted
  89.  
  90.          $ENV{'PATH'} = '/bin:/usr/bin';
  91.          delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
  92.  
  93.          $path = $ENV{'PATH'};       # $path now NOT tainted
  94.          system "echo $data";        # Is secure now!
  95.  
  96.          open(FOO, "< $arg");        # OK - read-only file
  97.          open(FOO, "> $arg");        # Not OK - trying to write
  98.  
  99.          open(FOO,"echo $arg|");     # Not OK, but...
  100.          open(FOO,"-|")
  101.              or exec 'echo', $arg;   # OK
  102.  
  103.          $shout = `echo $arg`;       # Insecure, $shout now tainted
  104.  
  105.          unlink $data, $arg;         # Insecure
  106.          umask $arg;                 # Insecure
  107.  
  108.          exec "echo $arg";           # Insecure
  109.          exec "echo", $arg;          # Secure (doesn't use the shell)
  110.          exec "sh", '-c', $arg;      # Considered secure, alas!
  111.  
  112.          @files = <*.c>;             # Always insecure (uses csh)
  113.          @files = glob('*.c');       # Always insecure (uses csh)
  114.  
  115.      If you try to do something insecure, you will get a fatal error saying
  116.      something like "Insecure dependency" or "Insecure $ENV{PATH}".  Note that
  117.      you can still write an insecure ssssyyyysssstttteeeemmmm or eeeexxxxeeeecccc, but only by explicitly
  118.      doing something like the "considered secure" example above.
  119.  
  120.      LLLLaaaauuuunnnnddddeeeerrrriiiinnnngggg aaaannnndddd DDDDeeeetttteeeeccccttttiiiinnnngggg TTTTaaaaiiiinnnntttteeeedddd DDDDaaaattttaaaa
  121.  
  122.      To test whether a variable contains tainted data, and whose use would
  123.      thus trigger an "Insecure dependency" message, check your nearby CPAN
  124.      mirror for the _T_a_i_n_t._p_m module, which should become available around
  125.      November 1997.  Or you may be able to use the following _i_s__t_a_i_n_t_e_d()
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  137.  
  138.  
  139.  
  140.      function.
  141.  
  142.          sub is_tainted {
  143.              return ! eval {
  144.                  join('',@_), kill 0;
  145.                  1;
  146.              };
  147.          }
  148.  
  149.      This function makes use of the fact that the presence of tainted data
  150.      anywhere within an expression renders the entire expression tainted.  It
  151.      would be inefficient for every operator to test every argument for
  152.      taintedness.  Instead, the slightly more efficient and conservative
  153.      approach is used that if any tainted value has been accessed within the
  154.      same expression, the whole expression is considered tainted.
  155.  
  156.      But testing for taintedness gets you only so far.  Sometimes you have
  157.      just to clear your data's taintedness.  The only way to bypass the
  158.      tainting mechanism is by referencing subpatterns from a regular
  159.      expression match.  Perl presumes that if you reference a substring using
  160.      $1, $2, etc., that you knew what you were doing when you wrote the
  161.      pattern.  That means using a bit of thought--don't just blindly untaint
  162.      anything, or you defeat the entire mechanism.  It's better to verify that
  163.      the variable has only good characters (for certain values of "good")
  164.      rather than checking whether it has any bad characters.  That's because
  165.      it's far too easy to miss bad characters that you never thought of.
  166.  
  167.      Here's a test to make sure that the data contains nothing but "word"
  168.      characters (alphabetics, numerics, and underscores), a hyphen, an at
  169.      sign, or a dot.
  170.  
  171.          if ($data =~ /^([-\@\w.]+)$/) {
  172.              $data = $1;                     # $data now untainted
  173.          } else {
  174.              die "Bad data in $data";        # log this somewhere
  175.          }
  176.  
  177.      This is fairly secure because /\w+/ doesn't normally match shell
  178.      metacharacters, nor are dot, dash, or at going to mean something special
  179.      to the shell.  Use of /.+/ would have been insecure in theory because it
  180.      lets everything through, but Perl doesn't check for that.  The lesson is
  181.      that when untainting, you must be exceedingly careful with your patterns.
  182.      Laundering data using regular expression is the _O_N_L_Y mechanism for
  183.      untainting dirty data, unless you use the strategy detailed below to fork
  184.      a child of lesser privilege.
  185.  
  186.      The example does not untaint $data if use locale is in effect, because
  187.      the characters matched by \w are determined by the locale.  Perl
  188.      considers that locale definitions are untrustworthy because they contain
  189.      data from outside the program.  If you are writing a locale-aware
  190.      program, and want to launder data with a regular expression containing
  191.      \w, put no locale ahead of the expression in the same block.  See the
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  203.  
  204.  
  205.  
  206.      SECURITY entry in the _p_e_r_l_l_o_c_a_l_e manpage for further discussion and
  207.      examples.
  208.  
  209.      SSSSwwwwiiiittttcccchhhheeeessss OOOOnnnn tttthhhheeee """"####!!!!"""" LLLLiiiinnnneeee
  210.  
  211.      When you make a script executable, in order to make it usable as a
  212.      command, the system will pass switches to perl from the script's #!
  213.      line.  Perl checks that any command line switches given to a setuid (or
  214.      setgid) script actually match the ones set on the #! line.  Some Unix and
  215.      Unix-like environments impose a one-switch limit on the #!  line, so you
  216.      may need to use something like -wU instead of -w -U under such systems.
  217.      (This issue should arise only in Unix or Unix-like environments that
  218.      support #! and setuid or setgid scripts.)
  219.  
  220.      CCCClllleeeeaaaannnniiiinnnngggg UUUUpppp YYYYoooouuuurrrr PPPPaaaatttthhhh
  221.  
  222.      For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a
  223.      known value, and each directory in the path must be non-writable by
  224.      others than its owner and group.  You may be surprised to get this
  225.      message even if the pathname to your executable is fully qualified.  This
  226.      is _n_o_t generated because you didn't supply a full path to the program;
  227.      instead, it's generated because you never set your PATH environment
  228.      variable, or you didn't set it to something that was safe.  Because Perl
  229.      can't guarantee that the executable in question isn't itself going to
  230.      turn around and execute some other program that is dependent on your
  231.      PATH, it makes sure you set the PATH.
  232.  
  233.      The PATH isn't the only environment variable which can cause problems.
  234.      Because some shells may use the variables IFS, CDPATH, ENV, and BASH_ENV,
  235.      Perl checks that those are either empty or untainted when starting
  236.      subprocesses. You may wish to add something like this to your setid and
  237.      taint-checking scripts.
  238.  
  239.          delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV safer
  240.  
  241.      It's also possible to get into trouble with other operations that don't
  242.      care whether they use tainted values.  Make judicious use of the file
  243.      tests in dealing with any user-supplied filenames.  When possible, do
  244.      opens and such aaaafffftttteeeerrrr properly dropping any special user (or group!)
  245.      privileges. Perl doesn't prevent you from opening tainted filenames for
  246.      reading, so be careful what you print out.  The tainting mechanism is
  247.      intended to prevent stupid mistakes, not to remove the need for thought.
  248.  
  249.      Perl does not call the shell to expand wild cards when you pass ssssyyyysssstttteeeemmmm
  250.      and eeeexxxxeeeecccc explicit parameter lists instead of strings with possible shell
  251.      wildcards in them.  Unfortunately, the ooooppppeeeennnn, gggglllloooobbbb, and backtick functions
  252.      provide no such alternate calling convention, so more subterfuge will be
  253.      required.
  254.  
  255.      Perl provides a reasonably safe way to open a file or pipe from a setuid
  256.      or setgid program: just create a child process with reduced privilege who
  257.      does the dirty work for you.  First, fork a child using the special ooooppppeeeennnn
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  269.  
  270.  
  271.  
  272.      syntax that connects the parent and child by a pipe.  Now the child
  273.      resets its ID set and any other per-process attributes, like environment
  274.      variables, umasks, current working directories, back to the originals or
  275.      known safe values.  Then the child process, which no longer has any
  276.      special permissions, does the ooooppppeeeennnn or other system call.  Finally, the
  277.      child passes the data it managed to access back to the parent.  Because
  278.      the file or pipe was opened in the child while running under less
  279.      privilege than the parent, it's not apt to be tricked into doing
  280.      something it shouldn't.
  281.  
  282.      Here's a way to do backticks reasonably safely.  Notice how the eeeexxxxeeeecccc is
  283.      not called with a string that the shell could expand.  This is by far the
  284.      best way to call something that might be subjected to shell escapes: just
  285.      never call the shell at all.
  286.  
  287.          use English;
  288.          die "Can't fork: $!" unless defined $pid = open(KID, "-|");
  289.          if ($pid) {           # parent
  290.              while (<KID>) {
  291.                  # do something
  292.              }
  293.              close KID;
  294.          } else {
  295.              my @temp = ($EUID, $EGID);
  296.              $EUID = $UID;
  297.              $EGID = $GID;    #      initgroups() also called!
  298.              # Make sure privs are really gone
  299.              ($EUID, $EGID) = @temp;
  300.              die "Can't drop privileges"
  301.                      unless $UID == $EUID  && $GID eq $EGID;
  302.              $ENV{PATH} = "/bin:/usr/bin";
  303.              exec 'myprog', 'arg1', 'arg2'
  304.                  or die "can't exec myprog: $!";
  305.          }
  306.  
  307.      A similar strategy would work for wildcard expansion via glob, although
  308.      you can use readdir instead.
  309.  
  310.      Taint checking is most useful when although you trust yourself not to
  311.      have written a program to give away the farm, you don't necessarily trust
  312.      those who end up using it not to try to trick it into doing something
  313.      bad.  This is the kind of security checking that's useful for set-id
  314.      programs and programs launched on someone else's behalf, like CGI
  315.      programs.
  316.  
  317.      This is quite different, however, from not even trusting the writer of
  318.      the code not to try to do something evil.  That's the kind of trust
  319.      needed when someone hands you a program you've never seen before and
  320.      says, "Here, run this."  For that kind of safety, check out the Safe
  321.      module, included standard in the Perl distribution.  This module allows
  322.      the programmer to set up special compartments in which all system
  323.      operations are trapped and namespace access is carefully controlled.
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  335.  
  336.  
  337.  
  338.      SSSSeeeeccccuuuurrrriiiittttyyyy BBBBuuuuggggssss
  339.  
  340.      Beyond the obvious problems that stem from giving special privileges to
  341.      systems as flexible as scripts, on many versions of Unix, set-id scripts
  342.      are inherently insecure right from the start.  The problem is a race
  343.      condition in the kernel.  Between the time the kernel opens the file to
  344.      see which interpreter to run and when the (now-set-id) interpreter turns
  345.      around and reopens the file to interpret it, the file in question may
  346.      have changed, especially if you have symbolic links on your system.
  347.  
  348.      Fortunately, sometimes this kernel "feature" can be disabled.
  349.      Unfortunately, there are two ways to disable it.  The system can simply
  350.      outlaw scripts with any set-id bit set, which doesn't help much.
  351.      Alternately, it can simply ignore the set-id bits on scripts.  If the
  352.      latter is true, Perl can emulate the setuid and setgid mechanism when it
  353.      notices the otherwise useless setuid/gid bits on Perl scripts.  It does
  354.      this via a special executable called ssssuuuuiiiiddddppppeeeerrrrllll that is automatically
  355.      invoked for you if it's needed.
  356.  
  357.      However, if the kernel set-id script feature isn't disabled, Perl will
  358.      complain loudly that your set-id script is insecure.  You'll need to
  359.      either disable the kernel set-id script feature, or put a C wrapper
  360.      around the script.  A C wrapper is just a compiled program that does
  361.      nothing except call your Perl program.   Compiled programs are not
  362.      subject to the kernel bug that plagues set-id scripts.  Here's a simple
  363.      wrapper, written in C:
  364.  
  365.          #define REAL_PATH "/path/to/script"
  366.          main(ac, av)
  367.              char **av;
  368.          {
  369.              execv(REAL_PATH, av);
  370.          }
  371.  
  372.      Compile this wrapper into a binary executable and then make _i_t rather
  373.      than your script setuid or setgid.
  374.  
  375.      See the program wwwwrrrraaaappppssssuuuuiiiidddd in the _e_g directory of your Perl distribution
  376.      for a convenient way to do this automatically for all your setuid Perl
  377.      programs.  It moves setuid scripts into files with the same name plus a
  378.      leading dot, and then compiles a wrapper like the one above for each of
  379.      them.
  380.  
  381.      In recent years, vendors have begun to supply systems free of this
  382.      inherent security bug.  On such systems, when the kernel passes the name
  383.      of the set-id script to open to the interpreter, rather than using a
  384.      pathname subject to meddling, it instead passes /_d_e_v/_f_d/_3.  This is a
  385.      special file already opened on the script, so that there can be no race
  386.      condition for evil scripts to exploit.  On these systems, Perl should be
  387.      compiled with -DSETUID_SCRIPTS_ARE_SECURE_NOW.  The CCCCoooonnnnffffiiiigggguuuurrrreeee program
  388.      that builds Perl tries to figure this out for itself, so you should never
  389.      have to specify this yourself.  Most modern releases of SysVr4 and BSD
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  401.  
  402.  
  403.  
  404.      4.4 use this approach to avoid the kernel race condition.
  405.  
  406.      Prior to release 5.003 of Perl, a bug in the code of ssssuuuuiiiiddddppppeeeerrrrllll could
  407.      introduce a security hole in systems compiled with strict POSIX
  408.      compliance.
  409.  
  410.      PPPPrrrrooootttteeeeccccttttiiiinnnngggg YYYYoooouuuurrrr PPPPrrrrooooggggrrrraaaammmmssss
  411.  
  412.      There are a number of ways to hide the source to your Perl programs, with
  413.      varying levels of "security".
  414.  
  415.      First of all, however, you _c_a_n'_t take away read permission, because the
  416.      source code has to be readable in order to be compiled and interpreted.
  417.      (That doesn't mean that a CGI script's source is readable by people on
  418.      the web, though.)  So you have to leave the permissions at the socially
  419.      friendly 0755 level.  This lets people on your local system only see your
  420.      source.
  421.  
  422.      Some people mistakenly regard this as a security problem.  If your
  423.      program does insecure things, and relies on people not knowing how to
  424.      exploit those insecurities, it is not secure.  It is often possible for
  425.      someone to determine the insecure things and exploit them without viewing
  426.      the source.  Security through obscurity, the name for hiding your bugs
  427.      instead of fixing them, is little security indeed.
  428.  
  429.      You can try using encryption via source filters (Filter::* from CPAN).
  430.      But crackers might be able to decrypt it.  You can try using the byte
  431.      code compiler and interpreter described below, but crackers might be able
  432.      to de-compile it.  You can try using the native-code compiler described
  433.      below, but crackers might be able to disassemble it.  These pose varying
  434.      degrees of difficulty to people wanting to get at your code, but none can
  435.      definitively conceal it (this is true of every language, not just Perl).
  436.  
  437.      If you're concerned about people profiting from your code, then the
  438.      bottom line is that nothing but a restrictive licence will give you legal
  439.      security.  License your software and pepper it with threatening
  440.      statements like "This is unpublished proprietary software of XYZ Corp.
  441.      Your access to it does not give you permission to use it blah blah blah."
  442.      You should see a lawyer to be sure your licence's wording will stand up
  443.      in court.
  444.  
  445. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  446.      the _p_e_r_l_r_u_n manpage for its description of cleaning up environment
  447.      variables.
  448.  
  449.  
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  467.  
  468.  
  469.  
  470.  
  471.  
  472.  
  473.  
  474.  
  475.  
  476.  
  477.  
  478.  
  479.  
  480.  
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.                                                                         PPPPaaaaggggeeee 8888
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.